#include "FileManager.h"
#include "Platforms.h"
#include <string.h>

FileManager* FileManager::s_instance = NULL;

FileManager::FileManager(void)
{
	m_root = NULL;
}

FileManager::~FileManager(void)
{
	SAFE_DEL(m_root);
}

FileManager* FileManager::GetInstance()
{
	if (s_instance == NULL)
	{
		s_instance = new FileManager();
	}
	return s_instance;
}

void FileManager::Destroy()
{
	if (s_instance != NULL)
	{
		delete s_instance;
	}
}

void FileManager::Init(const char *root)
{
	if (m_root != NULL)
	{
		SAFE_DEL(m_root);
	}
	m_root = new char[strlen(root) + 1];
	strcpy(m_root, root);
}

FILE* FileManager::Open(const char *fileName, const char *mode)
{
	char *fullPath = NULL;
	int lenRoot = strlen(m_root);
	int lenFileName = strlen(fileName);

	fullPath = new char[lenRoot + lenFileName + 1];
	memcpy(fullPath, m_root, lenRoot);
	strcpy(fullPath + lenRoot, fileName);

	FILE *pFile = fopen(fullPath, mode);

	if (pFile == NULL)
	{
		LOGI("Cannot open file %s.\n", fullPath);
	}

	else
	{
		//LOGI("Mo file %s thanh cong.\n", fullPath);
	}

	delete fullPath;

	return pFile;
}

void FileManager::Close(FILE *pFile)
{
	fclose(pFile);
}